package com.hariro.helper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
	private static final String DBNAME = "MyNewStyle.db";
	private static final int VERSION = 1;
	// private static final String SQL_CREATE_TABLE =
	// "CREATE TABLE tb_words(_id INTEGER PRIMARY KEY AUTOINCREMENT , english , chinese)";
	private static final String SQL_CREATE_TABLE = "CREATE TABLE tb_collect(_id INTEGER PRIMARY KEY AUTOINCREMENT , itemId , typeId)";
	private SQLiteDatabase db = null;

	public MySQLiteOpenHelper(Context context, String name,
			CursorFactory factory, int version) {
		super(context, DBNAME, null, VERSION);
		getConnection();
	}

	public SQLiteDatabase getConnection() {
		return db = this.getReadableDatabase();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(SQL_CREATE_TABLE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if (newVersion > oldVersion) {
			db.execSQL("DROP TABLE IF EXISTS tb_collect");
			onCreate(db);
		}
	}

	public Cursor selectCursor(String sql, String[] selectionArgs) {
		return db.rawQuery(sql, selectionArgs);
	}

	public int selectCount(String sql, String[] selectionArgs) {
		Cursor cursor = db.rawQuery(sql, selectionArgs);
		int count = cursor.getCount();
		if (cursor != null) {
			cursor.close();
		}
		return count;
	}

	public List<Map<String, Object>> selectData(String sql,
			String[] selectionArgs) {
		Cursor cursor = db.rawQuery(sql, selectionArgs);
		return cursorToList(cursor);
	}

	public boolean updateData(String sql, Object[] bindArgs) {
		try {
			db.execSQL(sql, bindArgs);
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return false;
	}

	public List<Map<String, Object>> cursorToList(Cursor cursor) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		while (cursor.moveToNext()) {
			String[] cols_name = cursor.getColumnNames();
			Map<String, Object> map = new HashMap<String, Object>();
			for (int i = 0; i < cols_name.length; i++) {
				Object value = null;
				switch (cursor.getType(i)) {
				case 1:
					value = cursor.getInt(i);
					break;
				case 2:
					value = cursor.getFloat(i);
					break;
				case 3:
					value = cursor.getString(i);
					break;
				case 4:
					value = cursor.getBlob(i);
					break;
				default:
					break;
				}
				map.put(cols_name[i], value);
			}
			list.add(map);
		}
		if (cursor != null) {
			cursor.close();
		}
		return list;
	}

	public void destroy() {
		if (db != null) {
			db.close();
		}
	}
}
